package com.ybw.redis.prevent.repeat.interceptor;

import com.alibaba.fastjson.JSON;
import com.ybw.redis.prevent.repeat.config.PreventRepeatConfig;
import com.ybw.redis.prevent.repeat.constant.ApiStatus;
import com.ybw.redis.prevent.repeat.constant.PreventRepeatConstant;
import com.ybw.redis.prevent.repeat.service.CommonService;
import com.ybw.redis.prevent.repeat.vo.res.base.ApiResultGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 防重拦截器
 *
 * @author ybw
 * @version V1.0
 * @className PreventRepeatInterceptor
 * @date 2022/6/2
 **/
@Slf4j
@Component
public class PreventRepeatInterceptor implements HandlerInterceptor {
    @Resource
    private CommonService commonService;
    @Resource
    private PreventRepeatConfig preventRepeatConfig;

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        if (!PreventRepeatConstant.Enable.Y.equals(preventRepeatConfig.getEnable())) {
            //1、防重机制不启用
            return true;
        }
        //2、获取防重码
        String code = request.getHeader("preCode");
        if (StringUtils.isBlank(code)) {
            //2.1 返回失败
            writeFail(response);
            return false;
        }
        //3、判断防重码是否存在
        boolean flag = commonService.checkExistAndDelKey(code);
        if (flag) {
            //3.1 防重码存在
            return true;
        }
        //3.2 防重码不存在
        writeFail(response);
        return false;
    }

    private void writeFail(HttpServletResponse response) throws IOException {
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(ApiResultGenerator.errorResult(ApiStatus.FAIL)));
        writer.close();
    }
}
